<?php
	require_once('query.php');

//FUNCTIONS:
//function trypurchase($userid, $storeitemid)
//function tradeCard($userid1, $userid2, $cardid1, $cardid2)
//function giveCard($userid1, $userid2, $cardid)
//function checkCardsForSale()
//function getCardInfoFromStore($storeitemid)

	// Functions should use transactions to ensure correct functionality.
	// Functions should use execute_query to prevent SQL injection attacks.
	// Functions should correctly handle the case where a user has multiples of the same card.
	// Functions should use the Possession table.  Usercards was added by the other group and will be difficult to use with our trade table.
	
	// Attempts to purchase a store item for a user.
	// Return true if the actions succeeds and false otherwise.
	function tryPurchase($userid, $storeitemid)
	{
		// Start a transaction
		start_transaction();
		
		// Get price of the store item
		$price_result = execute_query("SELECT price FROM StoreItem WHERE storeitemid = %s", $storeitemid);
		if (!$price_result)
			return NULL;
		$row = mysql_fetch_assoc($price_result);
		if (!row)
			return NULL;
		$price = $row['price'];
		mysql_free_result($price_result);
		
		// Gets the users points
		$points_result = execute_query("SELECT points FROM untol1_testdru.druuserpoints WHERE uid = '%s' AND tid = 147", $userid);
		if (!$points_result)
			return NULL;
		$row = mysql_fetch_assoc($points_result);
		if (!row)
			return NULL;
		$points = $row['points'];
		mysql_free_result($points_result);

		// Ensure the user has enough points
		if ($points < $price)
			return NULL;
		
		// Deduct cost from user's points
		$current_points = $points - $price;
		if (!execute_query("UPDATE untol1_testdru.druuserpoints SET points = %s WHERE uid = '%s' AND tid = 147", $current_points, $userid))
			return NULL;
		
		// Give user the cards associated with the store item
		$cards_result = execute_query("SELECT cardid FROM StoreItemCards WHERE storeitemid = %s", $storeitemid);
		if (!$cards_result)
			return NULL;
		while ($cards_row = mysql_fetch_assoc($cards_result))
		{
			if (!execute_query("INSERT INTO Possession (userid, cardid) VALUES ('%s', '%s')", $userid, $cards_row['cardid']))
				return NULL;
		}
		mysql_free_result($cards_result);
		
		// Commit changes
		commit();
		return $current_points;
	}
	
	function addToTrade($tradeid, $possessionid)
	{
		// Start a transaction
		start_transaction();
		
		// Ensure possession isn't already in trade
		$trade_possession_result = execute_query("SELECT EXISTS (SELECT * FROM untol1_testcb.TradePossession WHERE tradeid = %s AND possessionid = %s)", $tradeid, $possessionid);
		if (!$trade_possession_result) // trade_possession_result will be true if there already exists a possession id and a trade id meaning the card is already in a proposed trade
			return FALSE;
		if (mysql_result($trade_possession_result, 0))
			return FALSE;
		mysql_free_result($trade_possession_result);
		
		// Load data for the posession and the trade
		$possession_result = execute_query("SELECT * FROM Posession WHERE possessionid = %s", $possessionid);
		if (!$possession_result)
			return FALSE;
		$possession = mysql_fetch_assoc($possession_result);
		if (!$possession)
			return FALSE;
		mysql_free_result($possession_result);
		
		$trade_result = execute_query("SELECT * FROM Posession WHERE tradeid = %s", $tradeid);
		if (!$trade_result)
			return FALSE;
		$trade = mysql_fetch_assoc($trade_result);
		if (!$trade)
			return FALSE;
		mysql_free_result($trade_result);
		
		// Ensure possession belongs to one of the users
		if ($possession['userid'] != $trade['userid1'] && $possession['userid'] != $trade['userid2'])
			return FALSE;
		
		// Add possession to trade
		if (!execute_query("INSERT INTO TradePosessions (possessionid, tradeid) VALUES ('%s', %s)", $tradeid, $possessionid))
			return FALSE; // Returns false if unsuccessful
		
		// Update trade last modified time
		execute_query("UPDATE Trade SET lastmodified = NOW(), user1accepted = FALSE, user2accepted = FALSE WHERE tradeid = %s", $tradeid);
		
		// Commit changes
		commit();
		return TRUE;
	}
	
	function removeFromTrade($tradeid, $possessionid)
	{
		// Remove from trade
		if (!execute_query("REMOVE FROM TradePosessions WHERE tradeid = %s AND possessionid = %s)", $tradeid, $possessionid))
			return FALSE;

		// Update trade last modified time
		execute_query("UPDATE Trade SET lastmodified = NOW(), user1accepted = FALSE, user2accepted = FALSE WHERE tradeid = %s", $tradeid);
		
		// Commit changes
		commit();
		return TRUE;
	}
	
	function acceptTrade($tradeid, $userid, $timestamp)
	{
		// Get trade data
		$trade_result = execute_query("SELECT * FROM Posession WHERE tradeid = %s", $tradeid);
		if (!$trade_result)
			return FALSE;
		$trade = mysql_fetch_assoc($trade_result);
		if (!$trade)
			return FALSE;
		mysql_free_result($trade_result);

		// Make sure that the trade hasn't be modified
		if ($trade['lastmodified'] > $timestamp)
			return FALSE;
		
		// Get user ids
		$userid1 = $trade['userid1'];
		$userid2 = $trade['userid2'];
		
		// Make sure the user is actually in the trade
		$userindex = 0;
		if ($userid1 == $userid)
			$userindex = 1;
		else if ($userid2 == $userid)
			$userindex = 2;
		if ($userindex == 0)
			return FALSE;
		
		// Determine if the trade is complete
		if (
			($userindex == 1 && $trade['user2accepted']) ||
			($userindex == 2 && $trade['user1accepted'])
		)
		{
			// TODO: Perform trade
		}
		
		// Commit changes
		commit();
		return TRUE;
	}
	
	//Attempts to trade two cards between two users
	//Returns true if the trade completed, false if it did not
	function tradeCard($userid1, $userid2, $cardid1, $cardid2)
	{

		//Start Transaction
		start_transaction();
		
		//Check to see each user has specified card
		//Grab the result of where the User has the Card from Possession table
		$result1 = execute_query("SELECT possessionid FROM Possession WHERE cardid='%s' AND userid='%s'", $cardid1, $userid1);
		$result2 = execute_query("SELECT possessionid FROM Possession WHERE cardid='%s' AND userid='%s'", $cardid2, $userid2);
		
		//If there was a row for both queries, both users have those cards
		//If not, cancel the trade
		if($result1==null || $result2==null)
		{
			//One or both of the users did not have the specified card
			rollback();
			return FALSE;
		}

		//Grab the possession id's to keep track of which actual copy of the card is being traded
		$possess1 = mysql_result($result1, 0);
		$possess2 = mysql_result($result2, 0);

		//Both users have the cards they are supposed to, move on
		//Update the rows to change the cardids associated with each user
		$result1 = execute_query("UPDATE Possession SET cardid=$cardid2 WHERE userid='%s' AND cardid='%s' AND possessionid='%s'", $userid1, $cardid1, $possess1);
		$result2 = execute_query("UPDATE Possession SET cardid=$cardid1 WHERE userid='%s' AND cardid='%s' AND possessionid='%s'", $userid2, $cardid2, $possess2);

		//Check to make sure both of the updates worked
		if($result1==FALSE || $result2==FALSE)
		{
			//Exit the trade
			rollback();
			return FALSE;
		}

		//Both players had the cards, both cards were traded, everything went threw
		commit();
		return TRUE;
	}


	//Attempts to give a card from one user to another
	//Returns true if the transfer worked, false if it didnt
	function giveCard($userid1, $userid2, $cardid)
	{

		//Start transaction
		start_transation();

		//Check to see the user has specified card
		//Grab the result of where the User has the Card from Possession table
		$result = execute_query("SELECT possessionid FROM Possession WHERE cardid='%s' AND userid='%s'", $cardid, userid1);

		//Store possessionid for later
		$possess = mysql_result($result, 0);
		
		//If the query returned NULL then the user did not have the card, cancel give
		if($result==null)
		{
			rollback();
			return FALSE;
		}

		//User has the card, preceed with giving to other user
		//Add a new row to show the new user has the card now
		$result = execute_query("INSERT INTO Possession (possessionid, userid, cardid) VALUES ('%s', '%s', '%s')", $possess, $userid2, $cardid);
		
		//Make sure the new row was added correctly
		if($result==FALSE)
		{
			rollback();
			return FALSE;
		}

		//New user got given the card, delete it from the old user
		$result = execute_query("DELETE FROM Possession WHERE userid='%s' AND cardid='%s' AND possessionid='%s'", $userid1, $cardid, $possess);

		//Make sure the card was deleted from old user
		if($result==FALSE)
		{
			//Delete failed, remove card from new user, return false
			rollback();
			return FALSE;
		}

		//If made it to this point, user had card, was given to new user, taken away from old
		commit();
		return TRUE;
	}


	//Checks the store for cards for sale
	//Returns the list of cardids for cards that are for sale, or false if nothing was found
	function checkCardsForSale()
	{
		//Select all card ids from StoreItem
		$result = execute_query("SELECT cardid FROM StoreItem");
		
		//Make sure there are some results, return false if empty
		if($result==null)
		{
			return FALSE;
		}

		//Items were found, return them
		return $result;
	}

	//Gets information about a store item card
	//Returns the info, or false if nothing found
	function getCardInfoFromStore($storeitemid)
	{
	
		$result = execute_query("SELECT * FROM StoreItemCards WHERE storeitemid='%s'", $storeitemid);

		//Make sure there was a result, return false if there wasnt
		if($result==null)
		{
			return FALSE;
		}
	
		//Info was found, return it
		return $result;
	}

	
	

?>
